# -*- coding:UTF-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc
import wx.grid
import logging
import datetime
from src.bridge.getconfdata import ConfData

logging.basicConfig(filename="./log/homepagegui.log", filemode='w',
                    format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.DEBUG)


###########################################################################
## Class KanbPanel
###########################################################################

class KanbPanel(wx.Panel):

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL,
                 name=wx.EmptyString):
        wx.Panel.__init__(self, parent, id=id, pos=pos, size=size, style=style, name=name)

        self.cof = ConfData()
        self.coltitle = ["未开始", "进行中", "已暂停", "已完成", "已取消", "已关闭"]
        self.today = str(datetime.date.today()) #当前日期
        self.table = {"任务": "zt_task", "需求": "zt_story"}    #禅道数据库表名称
        self.taskcond = {"任务名称": "name", "指派给": "assignedTo", "优先级": "pri", "任务类型": "type", "结束日期": "deadline"}
        self.diststatus = {'wait': '未开始', 'doing': '进行中', 'done': '已完成', 'pause': '已暂停', 'cancel': '已取消',
                           'closed': '已关闭'}
        self.datacome = 0  # 数据来源方式 0来源爬虫，1来源数据库
        self.defaultrow = 10    #设置默认table_grid表格的行数为10
        self.values = self.get_taskp()  # 获取任务数据

        bSizer = wx.BoxSizer(wx.VERTICAL)

        gbSizer = wx.GridBagSizer(0, 0)
        gbSizer.SetFlexibleDirection(wx.BOTH)
        gbSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.tp_staticText = wx.StaticText(self, wx.ID_ANY, u"看板类型：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.tp_staticText.Wrap(-1)

        gbSizer.Add(self.tp_staticText, wx.GBPosition(0, 0), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        tp_choiceChoices = [u"任务", u"需求"]
        self.tp_choice = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, tp_choiceChoices, 0)
        self.tp_choice.SetSelection(0)
        gbSizer.Add(self.tp_choice, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                    5)

        self.xm_staticText = wx.StaticText(self, wx.ID_ANY, u"项目名称：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.xm_staticText.Wrap(-1)

        gbSizer.Add(self.xm_staticText, wx.GBPosition(0, 2), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.xm_Text = wx.StaticText(self, wx.ID_ANY, self.cof.get_one_value(section='info', key='projectname_cn'),
                                     wx.DefaultPosition, wx.DefaultSize, 0)
        self.xm_Text.Wrap(-1)

        self.xm_Text.SetFont(
            wx.Font(wx.NORMAL_FONT.GetPointSize(), wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,
                    False, wx.EmptyString))

        gbSizer.Add(self.xm_Text, wx.GBPosition(0, 3), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.cond_staticText = wx.StaticText(self, wx.ID_ANY, u"条件：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.cond_staticText.Wrap(-1)

        gbSizer.Add(self.cond_staticText, wx.GBPosition(1, 0), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        cond_choiceChoices = ["", u"任务名称", u"指派给", u"优先级", u"结束日期"]
        self.cond_choice = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cond_choiceChoices, 0)
        self.cond_choice.SetSelection(0)
        gbSizer.Add(self.cond_choice, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        cond_choice2Choices = ["=", "like", "<"]
        self.cond_choice2 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cond_choice2Choices, 0)
        self.cond_choice2.SetSelection(0)
        gbSizer.Add(self.cond_choice2, wx.GBPosition(1, 2), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.cond_textCtrl = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        self.cond_textCtrl.SetToolTip("请输入过滤关键字")
        gbSizer.Add(self.cond_textCtrl, wx.GBPosition(1, 3), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.refer_button = wx.Button(self, wx.ID_ANY, u"更 新", wx.DefaultPosition, wx.DefaultSize, 0)
        self.refer_button.SetLabelMarkup(u"更 新")
        self.refer_button.SetDefault()
        gbSizer.Add(self.refer_button, wx.GBPosition(1, 5), wx.GBSpan(1, 1), wx.ALL, 5)

        bSizer.Add(gbSizer, 0, 0, 5)

        self.table_grid = wx.grid.Grid(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0)

        # Grid
        if self.values[0] <= 10:
            self.table_grid.CreateGrid(10, 6)
        else:
            self.defaultrow = self.values[0]
            self.table_grid.CreateGrid(self.values[0], 6)
        self.table_grid.EnableEditing(False)
        self.table_grid.EnableGridLines(True)
        self.table_grid.EnableDragGridSize(False)
        self.table_grid.SetMargins(0, 0)

        # Columns
        self.table_grid.EnableDragColMove(False)
        self.table_grid.EnableDragColSize(True)
        self.table_grid.SetColLabelSize(30)
        self._set_table_label()
        self.table_grid.SetColLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)

        # Rows
        self.table_grid.AutoSizeRows()
        self.table_grid.EnableDragRowSize(True)
        self.table_grid.SetRowLabelSize(30)
        for r in range(self.defaultrow):
            self.table_grid.SetRowSize(r, 105)
        self.render_table_value(self.values[1])
        self.table_grid.SetRowLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)

        # Label Appearance

        # Cell Defaults
        self.table_grid.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        bSizer.Add(self.table_grid, 0, wx.RESERVE_SPACE_EVEN_IF_HIDDEN | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)

        self.SetSizer(bSizer)
        self.Layout()
        # bSizer.Fit(self)

        # Connect Events
        self.refer_button.Bind(wx.EVT_BUTTON, self.update_refer)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def update_refer(self, event):
        """
        更新按钮的更新事件
        :param event:
        :return:
        """
        event.GetEventObject().Disable()

        # storycond ={} 需求时，如上对应的字段
        try:
            tab = self.tp_choice.GetStringSelection()
            condkey = self.cond_choice.GetStringSelection()
            cond = self.cond_choice2.GetStringSelection()
            condvalue = self.cond_textCtrl.GetValue()
            from src.bridge.getconfdata import ConfData
            from src.bridge.getsqldata import MysqlData
            cofd = ConfData()
            msqld = MysqlData()
            if condkey.strip():
                self.table_grid.ClearGrid()
                if self.table[tab] == 'zt_task' and cond == 'like':
                    sdata = msqld.select_data(table=self.table[tab],
                                              showcoloum='status, assignedTo, type, pri, name, deadline',
                                              condition="{} like '%{}%'".format(self.taskcond[condkey], condvalue))
                    taskdata = msqld.get_task_data(cofd.get_one_value('info', 'projectname_cn'), sdata)
                    self.render_table_value(taskdata)
                elif self.table[tab] == 'zt_task' and cond != 'like':
                    sdata = msqld.select_data(table=self.table[tab],
                                              showcoloum='status, assignedTo, type, pri, name, deadline',
                                              condition="{} {} '{}'".format(self.taskcond[condkey], cond, condvalue))
                    taskdata = msqld.get_task_data(cofd.get_one_value('info', 'projectname_cn'), sdata)
                    self.render_table_value(taskdata)
            else:
                self.table_grid.ClearGrid()
                if self.table[tab] == 'zt_task':
                    taskdata = msqld.get_task_data(cofd.get_one_value('info', 'projectname_cn'))
                    self.render_table_value(taskdata)
        except BaseException as e:
            logging.error(e)
        finally:
            event.GetEventObject().Enable()
            event.Skip()

    def _set_table_label(self):
        """
        设置表格的 列表头 和列宽度
        :return:
        """
        try:
            for c in range(len(self.coltitle)):
                self.table_grid.SetColLabelValue(c, self.coltitle[c])
                self.table_grid.SetColSize(c, 150)
        except BaseException as e:
            logging.error(e)


    def get_taskp(self):
        """
        从数据库中获取 任务 列表
        :return: 状态想同的最大数量，用于确认表格行数；和 任务数据
        """
        try:
            # 获取配置文件中，base节点下，数据来源方式，可能存在没有该节点情况
            self.datacome = self.cof.get_one_value(section='base', key='datacome')
            logging.info(self.datacome)
        except BaseException as e:
            pass
        finally:
            if self.datacome == '1':
                # 如果detacome参数值为1，从数据库中去取数
                try:
                    countrows = []
                    from src.bridge.getsqldata import MysqlData
                    msql = MysqlData()
                    taskdata = msql.get_task_data(self.cof.get_one_value('info', 'projectname_cn'))
                    tb = self.tp_choice.GetStringSelection()
                    pj = self.xm_Text.GetLabel()
                    pid = msql.select_data(table='zt_project', showcoloum='id', condition="name like '%{}%'".format(pj))
                    logging.info(pid)
                    for p in range(len(pid)):
                        for key in self.diststatus.keys():
                            count = msql.select_data(table=self.table[tb], showcoloum='count(1)',
                                                   condition="project = '{}' and status = '{}'".format(pid[p][0], key))
                            countrows.append(count[0][0])
                    logging.info(countrows)
                    return [max(countrows), taskdata]
                    # self.render_table_value(taskdata)
                except BaseException as e:
                    logging.error(e)
            else:
                try:
                    url = self.cof.get_one_value(section='info', key='url')
                    user = self.cof.get_one_value(section='info', key='user')
                    pwd = self.cof.get_one_value(section='info', key='pwd')
                    pjname = self.cof.get_one_value(section='info', key='projectname_cn')
                    try:
                        opt = self.cof.get_one_value(section='base', key='opt') #若能正常获取，就去获取的值
                    except BaseException as e:
                        opt = 0 #获取不到，报错时，opt就为默认的0， 无头模式
                    from src.bridge.scrapydata import ScrapyData
                    scrdata = ScrapyData(url, user, pwd, pjname, opt)
                    rowN, taskdata = scrdata.scrapy_task()
                    return [rowN, taskdata]
                except BaseException as e:
                    logging.error(e)

    def render_table_value(self, datalist):
        """
        把通过爬虫或从数据库查询回来的 任务数据， 按照一定的格式，渲染展示在表格中
        :param datalist: 任务数据
        :return:
        """
        try:
            for data in datalist:
                # data数组中，第一个为任务状态，第1个为指派人，2个为任务类型，3个为任务等级 4个为任务名称 5个为计划完成时间
                coln = self.coltitle.index(data[0])
                value = "\n".join(["    ".join(data[1:4]), data[4], "    " * 3 + data[5]])
                for r in range(len(datalist)):
                    gtvalue = self.table_grid.GetCellValue(row=r, col=coln)
                    if gtvalue:
                        pass
                    elif data[5] < self.today and data[0] in ['未开始', '进行中']:
                        # 当数据中的完成时间，小于当前日期，同时 数据的状态为‘未开始 进行中’说明已经延期，延期的用红色文字，这样支持换行
                        self.table_grid.SetCellTextColour(r, coln, 'red')
                        render = wx.grid.GridCellAutoWrapStringRenderer()
                        self.table_grid.SetCellRenderer(r, coln, render)
                        self.table_grid.SetCellValue(r, coln, value)
                        break
                    else:
                        #表格单元格可能之前被设置成红色了， 所以需要再次渲染成默认，支持换行
                        render = wx.grid.GridCellAutoWrapStringRenderer()
                        self.table_grid.SetCellRenderer(r, coln, render)
                        self.table_grid.SetCellValue(r, coln, value)
                        break
        except BaseException as e:
            logging.error(e)
